package com.tusuo.stds.ui.integrity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hannesdorfmann.mosby.mvp.MvpPresenter;
import com.hannesdorfmann.mosby.mvp.MvpView;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.CompleteDetail;
import com.tusuo.stds.rest.UserInfo;
import com.tusuo.stds.rest.VipList;
import com.tusuo.stds.ui.BaseToolbarActivity;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.complete.CompleteQuestionActivity;
import com.tusuo.stds.ui.complete.CompleteQuestionActivity_;
import com.tusuo.stds.ui.pay.MyPayActivity_;
import com.tusuo.stds.ui.vip.VipActivity;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Locale;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import timber.log.Timber;

/**
 * Created by developer on 17-9-11.
 */

@SuppressLint("NewApi")
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(IntegrityDetailActivity.class)
@EActivity(R.layout.activity_integrity)
public class IntegrityDetailActivity extends BaseToolbarActivity {

    @ViewById(R.id.integrity_layout_background)
    LinearLayout layoutBackground;
    @ViewById(R.id.integrity_layout_pay)
    LinearLayout layoutPay;
    @ViewById(R.id.integrity_layout_hint)
    RelativeLayout layoutHint;
    @ViewById(R.id.integrity_layout_main)
    RelativeLayout layoutMain;
    @ViewById(R.id.integrity_layout_loading)
    RelativeLayout layoutLoading;
    @ViewById(R.id.vip_layout_price_group)
    LinearLayout layoutGroup;


    @ViewById(R.id.integrity_tv_title)
    TextView tvTitle;
    @ViewById(R.id.integrity_tv_correct)
    TextView tvCorrect;
    @ViewById(R.id.integrity_tv_continuous)
    TextView tvContinuous;
    @ViewById(R.id.integrity_tv_sum)
    TextView tvSum;
    @ViewById(R.id.integrity_tv_wrong)
    TextView tvWrong;

    @ViewById(R.id.integrity_btn_strengthen)
    Button btnStrengthen;

    @ViewById(R.id.integrity_lv_list)
    ListView lvList;

    @StringRes(R.string.err_msg_server)
    String mErrMsgServer;
    @Inject
    ApiHelper mApiHelper;

    private int mDataId;
    private int mType;
    private int mCompleteId;
    private CompleteDetail mCompleteDetail;
    private UserInfo mUserInfo;

    private TranslateAnimation animation_show;
    private TranslateAnimation animation_hide;
    private boolean isShowAnimationFinish = true;
    private boolean isHideAnimationFinish = true;
    private ArrayList<VipList.VipItem> mVipData;

    @AfterInject
    void initDI() {
        Injector.initIntegrityDetailActivityComponent().inject(this);
        if (getIntent().getExtras() != null) {
            mDataId = getIntent().getIntExtra("dataId",-1);
            mType = getIntent().getIntExtra("type",-1);
            mCompleteId = getIntent().getIntExtra("completeId",-1);
        }
    }

    @AfterViews
    void init() {
        setupUI(this);
        ToolbarOwner.Config config = new ToolbarOwner.Config("考法详情", true, null);
        mToolbarOwner.setConfig(config);

        if (mDataId != -1 && mType != -1 && mCompleteId != -1) {
            mApiHelper.getCompleteDetail(new GetCompleteDetailSubscriber(), mDataId, mType, mCompleteId);
        }
    }

    @UiThread
    void initData() {

        layoutMain.setVisibility(View.VISIBLE);
        layoutLoading.setVisibility(View.GONE);

        tvTitle.setText(mCompleteDetail.Title);
        tvSum.setText(mCompleteDetail.TotalCount + "");
        tvWrong.setText(mCompleteDetail.ErrorCount + "");
        tvContinuous.setText(mCompleteDetail.ContinueCount + "");
        tvCorrect.setText(String.format("%.2f%%", mCompleteDetail.CorrectRate * 100));

        switch (mCompleteDetail.Type) {
            case 1:
                layoutBackground.setBackgroundResource(R.color.background_change_qualified);
                break;
            case 2:
                layoutBackground.setBackgroundResource(R.color.background_blurry);
                break;
            case 3:
                layoutBackground.setBackgroundResource(R.color.background_question);
                break;
            default:
                layoutBackground.setBackgroundResource(R.color.background_blurry);
                break;
        }

        lvList.setAdapter(new IntegrityDetailAdapter(this, mCompleteDetail.ChapterRecordList));

        initAnimation();

        mApiHelper.getUserInfo(new GetUserInfoSubscriber());

    }

    private void initButton() {
        if (mUserInfo.VipLevel == 0) {
            // 不是VIP
            btnStrengthen.setText("开通会员即可强化训练");
            btnStrengthen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 弹出vip付费
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (layoutPay.getVisibility() != View.VISIBLE && isShowAnimationFinish && isHideAnimationFinish) {
                                layoutHint.setVisibility(View.VISIBLE);
                                layoutPay.setVisibility(View.VISIBLE);
                                layoutPay.startAnimation(animation_show);
                            }
                        }
                    });
                }
            });

        }else if (mUserInfo.VipLevel > 0) {
            // 是VIP
            btnStrengthen.setText("强化训练");
            btnStrengthen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 跳转到强化训练界面
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent();
                            intent.setClass(IntegrityDetailActivity.this, CompleteQuestionActivity_.class);
                            intent.putExtra("dataId",mDataId);
                            intent.putExtra("type",mType);
                            intent.putExtra("completeId",mCompleteId);
                            startActivity(intent);
                        }
                    });
                }
            });
        }
    }

    void initVipPay() {
        for (final VipList.VipItem item : mVipData) {
            View view = View.inflate(this,R.layout.item_vip_price,null);
            TextView tvMonth = (TextView) view.findViewById(R.id.item_vip_tv_month);
            TextView tvPrice = (TextView) view.findViewById(R.id.item_vip_tv_price);
            tvMonth.setText(item.Title);
            tvPrice.setText(String.format(Locale.SIMPLIFIED_CHINESE, "%.0f", item.Price));

            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    layoutPay.setVisibility(View.INVISIBLE);
                    Intent intent = new Intent();
                    intent.setClass(IntegrityDetailActivity.this, MyPayActivity_.class);
                    intent.putExtra("payType","vip");
                    intent.putExtra("vipId",item.Id);
                    intent.putExtra("vipMonth",item.Title);
                    intent.putExtra("vipPrice",item.Price);
                    startActivity(intent);
                }
            });

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT,1.0f);
            int px = Utils.dp2px(15, this);
            params.setMargins(0,0,px,0);

            layoutGroup.addView(view,params);
        }
    }

    void initAnimation() {
        animation_show = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 1,
                Animation.RELATIVE_TO_PARENT, 0);

        animation_show.setDuration(500);
        animation_show.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isShowAnimationFinish = false;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isShowAnimationFinish = true;
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });


        animation_hide = new TranslateAnimation(Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 0,
                Animation.RELATIVE_TO_PARENT, 1);

        animation_hide.setDuration(500);
        animation_hide.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isHideAnimationFinish = false;
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isHideAnimationFinish = true;
                layoutPay.setVisibility(View.GONE);
                layoutHint.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (layoutPay != null && layoutHint != null) {
            layoutPay.setVisibility(View.GONE);
            layoutHint.setVisibility(View.GONE);

        }

        if (mUserInfo != null) {
            mApiHelper.getUserInfo(new GetUserInfoSubscriber());
        }
    }

    @Click({R.id.vip_layout_iv_close,R.id.integrity_layout_hint})
    void hidePayLayout() {
        if (layoutPay.getVisibility() == View.VISIBLE && isShowAnimationFinish && isHideAnimationFinish) {
            layoutPay.startAnimation(animation_hide);
        }
    }



    @NonNull
    @Override
    public MvpPresenter createPresenter() {
        return new MvpPresenter() {
            @Override
            public void attachView(MvpView view) {
            }

            @Override
            public void detachView(boolean retainInstance) {
            }
        };
    }


    private class GetCompleteDetailSubscriber extends Subscriber<CompleteDetail> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            System.out.println("error" + e);
        }

        @Override
        public void onNext(CompleteDetail completeDetail) {
            if (completeDetail != null) {
                mCompleteDetail = completeDetail;
                initData();
            }
        }
    }

    private class GetUserInfoSubscriber extends Subscriber<UserInfo> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(final UserInfo userInfo) {
            if (userInfo.checkState(IntegrityDetailActivity.this)) {
                mUserInfo = userInfo;
                initButton();
                mApiHelper.getVipList(new GetVipListSubscriber());
            }

        }
    }

    private class GetVipListSubscriber extends Subscriber<VipList> {

        @Override
        public void onCompleted() {

        }

        @Override
        public void onError(Throwable e) {
            System.out.println("error" + e);

        }

        @Override
        public void onNext(VipList vipList) {
            if (vipList.Data != null && mVipData == null) {
                mVipData = vipList.Data;
                initVipPay();
            }
        }
    }

}
